package com.example.hrsystem.ui.approval.leave;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalStatus;
import com.example.hrsystem.workflow.ApprovalUtils;
import com.example.hrsystem.workflow.ApprovalViewModel;
import com.example.hrsystem.workflow.model.LeaveRequest;

/**
 * 请假申请详情Activity
 * 显示请假申请的详细信息和审批状态
 */
public class LeaveRequestDetailActivity extends AppCompatActivity {
    private ApprovalViewModel viewModel;
    private TextView requestNumberTextView;
    private TextView leaveTypeTextView;
    private TextView startDateTextView;
    private TextView endDateTextView;
    private TextView daysTextView;
    private TextView reasonTextView;
    private TextView statusTextView;
    private TextView createTimeTextView;
    private TextView updateTimeTextView;
    private ProgressBar progressBar;
    private EditText commentEditText;
    private Button approveButton;
    private Button rejectButton;
    
    private int currentUserId = 1000; // 默认用户ID，实际应用中应从登录信息获取
    private boolean isApprover = false; // 当前用户是否是审批人
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leave_request_detail);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);

        // 初始化UI组件
        initUI();

        // 获取并显示请假申请详情
        int leaveRequestId = getIntent().getIntExtra("leave_request_id", -1);
        if (leaveRequestId != -1) {
            loadLeaveRequestDetail(leaveRequestId);
        } else {
            Toast.makeText(this, "未找到请假申请信息", Toast.LENGTH_SHORT).show();
            finish();
        }

        // 设置审批按钮点击事件
        setupApprovalButtons();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        requestNumberTextView = findViewById(R.id.request_number_text_view);
        leaveTypeTextView = findViewById(R.id.leave_type_text_view);
        startDateTextView = findViewById(R.id.start_date_text_view);
        endDateTextView = findViewById(R.id.end_date_text_view);
        daysTextView = findViewById(R.id.days_text_view);
        reasonTextView = findViewById(R.id.reason_text_view);
        statusTextView = findViewById(R.id.status_text_view);
        createTimeTextView = findViewById(R.id.create_time_text_view);
        updateTimeTextView = findViewById(R.id.update_time_text_view);
        progressBar = findViewById(R.id.progress_bar);
        commentEditText = findViewById(R.id.comment_edit_text);
        approveButton = findViewById(R.id.approve_button);
        rejectButton = findViewById(R.id.reject_button);
    }

    /**
     * 加载请假申请详情
     */
    private void loadLeaveRequestDetail(int leaveRequestId) {
        LeaveRequest leaveRequest = viewModel.getLeaveRequestById(leaveRequestId);
        if (leaveRequest != null) {
            displayLeaveRequestDetail(leaveRequest);
            checkApprovalPermission(leaveRequest);
        } else {
            Toast.makeText(this, "加载请假申请详情失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示请假申请详情
     */
    private void displayLeaveRequestDetail(LeaveRequest leaveRequest) {
        // 请求编号 (暂时使用ID代替，因为没有requestNumber字段)
        requestNumberTextView.setText("请假申请 #" + leaveRequest.getId());
        leaveTypeTextView.setText(leaveRequest.getLeaveType());
        // 请假时间
        startDateTextView.setText(ApprovalUtils.formatDateTime(leaveRequest.getStartTime()));
        endDateTextView.setText(ApprovalUtils.formatDateTime(leaveRequest.getEndTime()));
        daysTextView.setText(String.valueOf(leaveRequest.getDays()));
        reasonTextView.setText(leaveRequest.getReason());
        
        // 设置状态显示
        String status = leaveRequest.getStatus();
        statusTextView.setText(ApprovalUtils.getStatusDisplayName(status));
        statusTextView.setTextColor(ApprovalUtils.getStatusColor(this, status));
        
        createTimeTextView.setText(ApprovalUtils.formatDateTime(leaveRequest.getCreatedAt()));
        updateTimeTextView.setText(ApprovalUtils.formatDateTime(leaveRequest.getUpdatedAt()));
    }

    /**
     * 检查当前用户是否有审批权限
     */
    private void checkApprovalPermission(LeaveRequest leaveRequest) {
        // 这里简化处理，实际应用中应该根据组织结构判断用户是否有审批权限
        // 示例中，假设用户ID为1001及以上的用户是审批人
        isApprover = currentUserId >= 1001;
        
        // 检查状态是否是待审批
        boolean isPending = "PENDING".equals(leaveRequest.getStatus());
        
        // 根据权限和状态显示或隐藏审批按钮
        if (isApprover && isPending) {
            commentEditText.setVisibility(View.VISIBLE);
            approveButton.setVisibility(View.VISIBLE);
            rejectButton.setVisibility(View.VISIBLE);
        } else {
            commentEditText.setVisibility(View.GONE);
            approveButton.setVisibility(View.GONE);
            rejectButton.setVisibility(View.GONE);
        }
    }

    /**
     * 设置审批按钮点击事件
     */
    private void setupApprovalButtons() {
        // 监听加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            approveButton.setEnabled(!isLoading);
            rejectButton.setEnabled(!isLoading);
        });

        // 监听操作结果
        viewModel.getOperationSuccess().observe(this, isSuccess -> {
            if (isSuccess != null && isSuccess) {
                // 刷新页面，显示更新后的状态
                int leaveRequestId = getIntent().getIntExtra("leave_request_id", -1);
                if (leaveRequestId != -1) {
                    loadLeaveRequestDetail(leaveRequestId);
                }
            }
        });

        // 监听错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(LeaveRequestDetailActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });

        // 批准按钮点击事件
        approveButton.setOnClickListener(v -> {
            String comment = commentEditText.getText().toString().trim();
            if (comment.isEmpty()) {
                Toast.makeText(LeaveRequestDetailActivity.this, "请填写审批意见", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取任务ID（简化处理，实际应用中应该从流程实例中获取）
            // 这里假设我们已经有了任务ID
            long taskId = 1; // 示例任务ID，实际应用中需要从流程中获取
            viewModel.approveTask(taskId, currentUserId, comment);
        });

        // 拒绝按钮点击事件
        rejectButton.setOnClickListener(v -> {
            String comment = commentEditText.getText().toString().trim();
            if (comment.isEmpty()) {
                Toast.makeText(LeaveRequestDetailActivity.this, "请填写拒绝理由", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取任务ID（简化处理，实际应用中应该从流程实例中获取）
            long taskId = 1; // 示例任务ID，实际应用中需要从流程中获取
            viewModel.rejectTask(taskId, currentUserId, comment);
        });
    }
}